﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using Telerik.Web.UI;
namespace BSPortal.Usercontrol.Admin.Book
{
    public partial class frmCategory : System.Web.UI.Page
    {
        private short id = 0;
        private MainService service =new MainService();
        protected const string unreadPattern = @"\(\d+\)";

        protected void RadTreeView1_ContextMenuItemClick(object sender, RadTreeViewContextMenuEventArgs e)
        {
            RadTreeNode clickedNode = e.Node;

            switch (e.MenuItem.Value)
            {
                case "Copy":
                    RadTreeNode clonedNode = clickedNode.Clone();
                    clonedNode.Text = string.Format("Copy of {0}", clickedNode.Text);
                    clickedNode.InsertAfter(clonedNode);
                    //set node's value so we can find it in startNodeInEditMode
                    clonedNode.Value = clonedNode.GetFullPath("/");
                    clonedNode.Selected = true;
                    startNodeInEditMode(clonedNode.Value);
                    break;
                case "NewFolder":
                    RadTreeNode newFolder = new RadTreeNode(string.Format("New Folder {0}", clickedNode.Nodes.Count + 1));
                    newFolder.Selected = true;
                    newFolder.ImageUrl = clickedNode.ImageUrl;
                    clickedNode.Nodes.Add(newFolder);
                    clickedNode.Expanded = true;
                    //update the number in the brackets
                    if (Regex.IsMatch(clickedNode.Text, unreadPattern))
                        clickedNode.Text = Regex.Replace(clickedNode.Text, unreadPattern, "(" + clickedNode.Nodes.Count.ToString() + ")");
                    else
                        clickedNode.Text += string.Format(" ({0})", clickedNode.Nodes.Count);
                    clickedNode.Font.Bold = true;
                    //set node's value so we can find it in startNodeInEditMode
                    newFolder.Value = "0";
                    startNodeInEditMode(newFolder.Value);
                    //service.CreateCateogry(clickedNode.Text, "", short.Parse(e.Node.Value));
                    break;
                case "EmptyFolder":
                    emptyFolder(clickedNode, true);
                    break;
                case "MarkAsRead":
                    emptyFolder(clickedNode, false);
                    break;
                case "Delete":
                    clickedNode.Remove();
                    service.DeleteCategory(short.Parse(e.Node.Value));
                    break;
                case "Rename":
                    //service.UpdateCategory(short.Parse(e.Node.Value),e.Node.Text,"")
                    break;
            }
        }

        private void startNodeInEditMode(string nodeValue)
        {
            //find the node by its Value and edit it when page loads
            
            string js = "Sys.Application.add_load(editNode); function editNode(){ ";
            js += "var tree = $find(\"" + RadTreeView1.ClientID + "\");";
            js += "var node = tree.findNodeByValue('" + nodeValue + "');";
            js += "if (node) node.startEdit();";
            js += "Sys.Application.remove_load(editNode);};";

            RadScriptManager.RegisterStartupScript(Page, Page.GetType(), "nodeEdit", js, true);
        }

        protected void RadTreeView1_NodeEdit(object sender, RadTreeNodeEditEventArgs e)
        {
            e.Node.Text = e.Text;
            if(e.Node.Value=="0")
            {
                service.CreateCateogry(e.Text, "", short.Parse(e.Node.ParentNode.Value),true);
            }
            else
            {
                service.UpdateCategory(short.Parse(e.Node.Value), e.Text, "", short.Parse(e.Node.ParentNode.Value),true);
            }
            LoadCategory();
        }

        //this method is used by Mark All as Read and Empty this folder 
        protected void emptyFolder(RadTreeNode node, bool removeChildNodes)
        {
            node.Font.Bold = false;
            node.Text = Regex.Replace(node.Text, unreadPattern, "");

            if (removeChildNodes)
            {
                //Empty this folder is clicked
                for (int i = node.Nodes.Count - 1; i >= 0; i--)
                {
                    node.Nodes.RemoveAt(i);
                }
            }
            else
            {
                //Mark all as read is clicked
                foreach (RadTreeNode child in node.Nodes)
                {
                    emptyFolder(child, removeChildNodes);
                }
            }
        }    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCategory();
            }
        }

        private void LoadCategory()
        {
            RadTreeNode nodeBookRoot = new RadTreeNode("Sách", "1");
            RadTreeNode nodeElectronicRoot = new RadTreeNode("Thiết bị điện tử", "2");
            RadTreeNode nodeHouseRoot = new RadTreeNode("Đồ gia dụng", "3");
            nodeBookRoot.AllowEdit = nodeBookRoot.AllowDrag = nodeBookRoot.AllowDrop = false;
            nodeElectronicRoot.AllowEdit = nodeElectronicRoot.AllowDrag = nodeElectronicRoot.AllowDrop = false;
            nodeHouseRoot.AllowEdit = nodeHouseRoot.AllowDrag = nodeHouseRoot.AllowDrop = false;
            RadTreeNode nodeBook = GetAllNodeByListCategory(nodeBookRoot,1);
            RadTreeNode nodeElectronic = GetAllNodeByListCategory(nodeElectronicRoot,2);
            RadTreeNode nodeHouse = GetAllNodeByListCategory(nodeHouseRoot,3);
            RadTreeView1.Nodes.Add(nodeBookRoot);
            RadTreeView1.Nodes.Add(nodeElectronicRoot);
            RadTreeView1.Nodes.Add(nodeHouseRoot);
        }

        public RadTreeNode GetAllNodeByListCategory(RadTreeNode root,short parentCategoyId)
        {
            var radeNode = new RadTreeNode();
            var listCategory = service.GetListChildCategoryByParent(parentCategoyId);

            foreach (var category in listCategory)
            {
                var node = new RadTreeNode(category.Name, category.CategoryId.ToString());
                root.Nodes.Add(node);
                RadTreeNode node2 = GetAllNodeByListCategory(node, category.CategoryId);
            }
            return radeNode;
        }
    }
}
